package com.easyui.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.easyui.bean.Student;
import com.easyui.bean.Teacher;
import com.easyui.common.SelTeacher;

public class GetTeacherServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/json;charset=utf-8");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		
		List<Teacher> tlist = null;
		List<Map> initList = null;
		JSONObject jsonAll= null;//装所有信息，包括total参数
		
		int page = Integer.parseInt(request.getParameter("page"));
		int rows = Integer.parseInt(request.getParameter("rows"));//page和rows需要返回
		String orderBy = request.getParameter("order");//排序方式,不用返回
		String sortName = request.getParameter("sort");//排序字段,不用返回
		
		String tno = request.getParameter("tno");
		String tname = request.getParameter("tname");
		String sex = request.getParameter("sex");
		
		int totalRecords = 0;
		jsonAll = new JSONObject();
		SelTeacher st = new SelTeacher();
		Teacher at = st.getTeacher(tno, tname, sex);
		initList = st.getAllTeachers(orderBy, sortName, at);//返回所有老师信息
		tlist = st.getSpeTeachers(initList, page, rows, orderBy, sortName, at);
		
		if (tlist != null && tlist.size() > 0) {
			JSONArray jsonTeacher = new JSONArray();//装老师信息
			
			for (int i = 0; i < tlist.size(); i++) {
				Teacher t = (Teacher)tlist.get(i);
				
				JSONObject j = new JSONObject();
				j.put("tno", t.getTno());
				j.put("tname", t.getTname());
				j.put("sex", t.getSex());
				if(t.getOwnProject() != null && t.getOwnProject().size() > 0) {
					j.put("proNum", t.getOwnProject().size());
				} else {
					j.put("proNum", 0);
				}
				jsonTeacher.add(j);
			}
			
			totalRecords = initList.size();
			jsonAll.put("total", totalRecords);
			jsonAll.put("rows", jsonTeacher);
			
			//out.println(" { \"total\": " + totalRecords + ", \"rows\": " + json.toString() + "}");
		} else {
			totalRecords = 1;
			JSONArray jsonTeacher = new JSONArray();//装老师信息
			jsonAll.put("total", totalRecords);
			JSONObject j = new JSONObject();
			j.put("tno", "");
			j.put("tname", "");
			j.put("sex", "");
			j.put("proNum", "");
			jsonTeacher.add(j);
			jsonAll.put("rows", jsonTeacher);
		}
		
		out.print(jsonAll);
		
		out.flush();
		out.close();
	}

}
